package repository

import (
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/model"
)

type miaoTerminalRepository struct{}

func (r miaoTerminalRepository) FindListByOrgID(orgId int64) (li []model.MiaoClient, err error) {
	err = db.GetDB().Where("device_id in (select idp_map_org_device.device_id from idp_map_org_device where idp_org_id =?)",
		orgId).Find(&li).Error
	return
}

// FindListByUid 查询用户能看见的所有设备列表，
func (r miaoTerminalRepository) FindListByUid(uid int64) (li []model.MiaoClient, err error) {
	err = db.GetDB().Where(
		"device_id in ( select idp_map_org_device.device_id from idp_map_org_device where idp_org_id in ( select idp_org_id from idp_map_org_user where user_id =? ))",
		uid).Find(&li).Error
	return
}

func (r miaoTerminalRepository) Save(u model.MiaoClient) (err error) {
	return db.GetDB().Save(&u).Error
}

func (r miaoTerminalRepository) FindProbableList(bios, boardSerial, diskSerial, mac, hostname string) (li []model.MiaoClient, err error) {
	err = db.GetDB().Where("bios_serial = ? or main_board_serial = ? or hard_disk_serial = ? "+
		" or active_mac= ? or hostname = ? ",
		bios, boardSerial, diskSerial, mac, hostname).Find(&li).Error
	return
}

func (r miaoTerminalRepository) FindPage(page model.PageInfo, hostname, ip string) (li []model.MiaoClient, total int64, err error) {
	err = db.GetDB().Where("hostname like ? and ip like ?", "%"+hostname+"%", "%"+ip+"%").Find(&li).
		Limit(page.PageSize).Offset((page.Page - 1) * page.PageSize).Count(&total).Error
	return
}

func (r miaoTerminalRepository) Find(id int64) (o model.MiaoClient, err error) {
	err = db.GetDB().Where("device_id = ?", id).Find(&o).Error
	return
}

func (r miaoTerminalRepository) FindAll() (li []model.MiaoClient, err error) {
	err = db.GetDB().Where("device_id >0 ").Find(&li).Error
	return
}
